package com.cyj.dream.core.util.captcha;

import cn.hutool.captcha.CaptchaUtil;
import cn.hutool.captcha.LineCaptcha;
import cn.hutool.captcha.ShearCaptcha;
import cn.hutool.captcha.generator.MathGenerator;
import cn.hutool.core.lang.Console;
import com.cyj.dream.core.constant.Constant;
import com.cyj.dream.core.util.nosql.RedisUtil;
import com.cyj.dream.core.util.user.UUIDUtils;
import lombok.extern.slf4j.Slf4j;
import org.springframework.beans.factory.annotation.Autowired;

import java.util.HashMap;
import java.util.Map;

/**
 * @Description: 图形或者数字验证器
 * @BelongsProject: DreamChardonnay
 * @BelongsPackage: com.cyj.dream.core.util.captcha
 * @Author: ChenYongJia
 * @CreateTime: 2021-09-26 13:34
 * @Email: chen87647213@163.com
 * @Version: 1.0
 */
@Slf4j
public class CaptchaUtils {

    @Autowired
    private static RedisUtil redisUtil;

    /**
     * 生成图形验证码并返回给前端
     *
     * @return java.util.Map<java.lang.String, java.lang.Object>
     * @date 2021/5/29 15:20
     * @author ChenYongJia
     * @version 1.0
     */
    public static Map<String, Object> getImg() {
        // HuTool定义图形验证码的长和宽,验证码的位数，干扰线的条数
        LineCaptcha lineCaptcha = CaptchaUtil.createLineCaptcha(200, 100, 4, 2);
        String img = lineCaptcha.getImageBase64();
        String code = lineCaptcha.getCode();
        String UUID = UUIDUtils.getUUIDNoHave();
        // 存入 code 验证码结果，key 为生成的UUID（并设置三分钟有效期）
        redisUtil.set(UUIDUtils.getUUIDNoHave(), code, 180);
        log.info("图形验证码的code为：{}", code);
        Map<String, Object> map = new HashMap<>(Constant.INITIAL_CAPACITY);
        map.put("captcha", "data:image/png;base64," + img);
        map.put("verify", UUID);
        return map;
    }

    /**
     * 生成数字计算验证码
     *
     * @return java.lang.String
     * @date 2021/5/29 15:28
     * @author ChenYongJia
     * @version 1.0
     */
    public static String getNumberCode() {
        ShearCaptcha captcha = CaptchaUtil.createShearCaptcha(200, 45, 4, 4);
        // 自定义验证码内容为四则运算方式
        captcha.setGenerator(new MathGenerator());
        // 重新生成code
        captcha.createCode();
        //新的验证码
        return captcha.getCode();
    }

    public static void main(String[] args) {
        // 打印--生成图形验证码并返回给前端方法的结果
        Console.log(CaptchaUtils.getImg());
        // 打印--生成数字计算验证码方法的结果
        Console.log(CaptchaUtils.getNumberCode());
    }

}
